package cn.wzl.recognition.training;

import cn.wzl.recognition.bpnn.PictureRecognitionBPNN;

public class Trainer {

    public final double[][] inputValue;
    public final double[][] expectedValue;
    public final double[][] result;
    public final int size;
    public final PictureRecognitionBPNN bp;

    public Trainer(double[][] inputValue, double[][] expectedValue, double[][] result, int size, PictureRecognitionBPNN bp) {
        this.inputValue = inputValue;
        this.expectedValue = expectedValue;
        this.result = result;
        this.size = size;
        this.bp = bp;
    }

    public void training(int times) {
        for(int i = 1; i <= times; i ++){
            double errRate = trainingOneTime();
            System.out.println("[" + i + "/" + times + "] error rate:" + errRate);
        }
    }

    public double trainingOneTime(){
        int err = 0;
        System.out.print("training with " + inputValue.length + "|" + expectedValue.length + ". . . . . .");
        for (int i = 0; i < size; i++) {
            //showExample(inputValue[i], result[i]);
            int res = bp.training(inputValue[i], expectedValue[i]);
            if(res != (int) result[i][0]) {
                err ++;
            }
        }
        System.out.println("done." );
        return err * 1d / inputValue.length;
    }

    private void showExample(double[] inputValue, double[] result) {
        for(int i = 0; i < 28; i ++) {
            for(int j = 0; j < 28; j ++) {
                System.out.print(inputValue[i*28 + j] + " ");
            }
            System.out.println("");
        }
        System.out.println(result[0]);
    }

}
